import json
import sys
import io
import time

# 设置sys.stdout的编码为UTF-8
sys.stdout.reconfigure(encoding='utf-8')
# 创建一个新的输出流，并设置编码为UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# 将 当且路径 添加到path中
sys.path.append(r'.')
from DrissionPage import ChromiumPage


def load_param_datas_from_file(file_path):
    with open(file_path, "r", encoding='utf-8') as f:
        json_file_datas = json.loads(f.read())  # load的传入参数为字符串类型
        return json_file_datas
 
def down_excel_file(tab,dateDivEle,dayText,dayFile,savePath):
    # 下载某日数据
    dayButton = dateDivEle.ele('tag:button@@text()=' + dayText)
    dayButton.click() # 选择时间
    time.sleep(3) 

    down_link = tab.ele('tag:a@@text():下载') # 模糊匹配下载按钮
    mission = down_link.click.to_download(savePath, dayFile)  # 点击一个会触发下载的链接，同时设置下载路径和文件名
    mission.wait()  # 等待下载结束
    time.sleep(1) 

def  item_rank_down_excel(param_file):
    print(param_file)
    json_file_datas = load_param_datas_from_file(param_file)
    print (json_file_datas)
    downUrl = json_file_datas['downUrl']
    port = json_file_datas['port']
    dayDivClass = json_file_datas['dayDivClass']
    savePath = json_file_datas['savePath']
    day30Text = json_file_datas['day30Text']
    day7Text = json_file_datas['day7Text']
    day1Text = json_file_datas['day1Text']

    page = ChromiumPage(addr_or_opts='127.0.0.1:' + str(port))

    tab = page.new_tab()  # 新建标签页，获取标签页对象
    tab.get(downUrl)
    # 等待页面加载
    tab.wait.load_start()

    # 下载30日数据
    dateDivEle = tab.ele('tag:div@@class=' + dayDivClass)

    down_excel_file(tab,dateDivEle,day30Text,'day30',savePath)
    down_excel_file(tab,dateDivEle,day7Text,'day7',savePath)
    down_excel_file(tab,dateDivEle,day1Text,'day1',savePath)

    tab.close()

def main():
    """
     src/sycm/down/item_rank_down_excel.data.json
    """
    py_name = sys.argv[0]
    param_file = 'item_rank_down_excel.data.json'
    if len(sys.argv) >= 2:
        param_file = sys.argv[1]

    item_rank_down_excel(param_file)


if __name__ == "__main__":
    main()


